package com.study.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "login", urlPatterns = { "/*" })
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        resp.setContentType("text/html;");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String request_uri = req.getRequestURI();
        String ctxPath = req.getContextPath();
        String uri = request_uri.substring(ctxPath.length());
        if (uri.equals("/")||uri.contains("login.jsp") || uri.contains("login")||uri.contains("index.jsp")
                ||uri.contains("css")
                ||uri.contains("img")
                ||uri.contains("plugins")) {
            chain.doFilter(request, response);
        } else {
            if (session.getAttribute("user") != null) {
                chain.doFilter(request, response);
            } else {
                PrintWriter out = resp.getWriter();
                out.println("您没有登录，请先登录！3秒后回到登录页面。");
                resp.setHeader("refresh", "3;url=" + ctxPath + "/homework/jsps/login.jsp");
                out.close();
                return;
            }
        }
    }

    @Override
    public void destroy() {

    }
    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
